package duoxiancheng;

/**
 * 死锁：过多的同步可能造成资源不释放
 * 从而相互等待，一般发生于同步中持有多个对象的锁
 */
public class sisuo {
    public static void main(String[] args) {
        Markup m1 = new Markup(1,"你");
        Markup m2 = new Markup(0,"我");

        m1.start();
        m2.start();
    }
}

//口红
class Lipstick{

}

//镜子
class Mirror{

}

//化妆
class Markup extends Thread{
    //加个静态，就代表一份，永远是一个口红一个镜子
    static Lipstick lips= new Lipstick();
    static Mirror mir = new Mirror();

    //选择
    int choice;
    //名字
    String name;

    public Markup(int choice, String name) {
        this.choice = choice;
        this.name = name;
    }

    @Override
    public void run() {
        //化妆
        makeup();
    }
//相互持有对方的对象锁，---->可能造成死锁
    private void makeup(){
        if (choice==0){
            synchronized (lips){//获得口红的锁
                System.out.println(this.name+"获得口红");
                //1s后想拥有镜子的锁
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                synchronized (mir){//死锁
//                    System.out.println(this.name+"想照镜子");
//                }
            }
            synchronized (mir){//解决
                    System.out.println(this.name+"想照镜子");
                }
        }else{
            synchronized (mir){//获得镜子的锁
                System.out.println(this.name+"获得镜子");
                //1s后想拥有口红的锁
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                synchronized (lips){//死锁
//                    System.out.println(this.name+"想要口红");
//                }
            }
            synchronized (lips){//解决
                System.out.println(this.name+"想要口红");
            }
        }
    }
}